﻿using System;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using Ent;
using Newtonsoft.Json;

namespace Travel.MVC.Controllers
{
    /// <summary>
    /// 用户票据操作
    /// </summary>
    public static class Token
    {
        /// <summary>
        /// 设置客户端票据
        /// </summary>
        /// <param name="httpContext">http上下文</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        public static void SetClientTicket(string userName, string userData)
        {
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userData);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
            authCookie.Value = FormsAuthentication.Encrypt(authTicket);
            authCookie.Path = FormsAuthentication.FormsCookiePath;
            authCookie.Domain = FormsAuthentication.CookieDomain;
            authCookie.Secure = FormsAuthentication.RequireSSL;
            authCookie.HttpOnly = true;
            HttpContext.Current.Response.Cookies.Set(authCookie);
        }

        /// <summary>
        /// 获取用户票据
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <param name="anonymousID">AnonymousID</param>
        /// <returns>
        /// 用户票据
        /// </returns>
        public static UserTicket GetUserTicket()
        {
            var user = System.Web.HttpContext.Current.User;
            var clientAuthenticated = user != null && user.Identity.IsAuthenticated;
            if (clientAuthenticated)
            {
                var clientTicket = (user.Identity as FormsIdentity).Ticket;
                var serverTicket = JsonConvert.DeserializeObject<UserTicket>(clientTicket.UserData);
                if (serverTicket != null)
                {
                    return serverTicket;
                }
            }
            return GenerateGuestTicket();
        }

        /// <summary>
        /// 生成一个游客票据
        /// </summary>
        /// <param name="anonymousID">AnonymousID</param>
        /// <returns>
        /// 游客票据
        /// </returns>
        private static UserTicket GenerateGuestTicket()
        {
            return new UserTicket()
            {
                IsGuest = true,
                //NickName = "游客",
                //UserName = "游客",
                //AnonymousID = anonymousID
            };
        }

        /// <summary>
        /// 清空客户端票据
        /// </summary>
        public static void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}